package com.jilefojing.controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.jilefojing.beans.data.enums.ResponseEnum;
import com.jilefojing.beans.data.manager.response.BannerData;
import com.jilefojing.beans.data.response.base.ResponseData;
import com.jilefojing.beans.enums.PlatformEnumForPublish;
import com.jilefojing.beans.enums.StatusEnumForPublish;
import com.jilefojing.beans.exception.UserContextException;
import com.jilefojing.beans.pojos.Banner;
import com.jilefojing.beans.pojos.enhanced.EnhancedBanner;
import com.jilefojing.beans.query.BannerQuery;
import com.jilefojing.beans.vo.Order;
import com.jilefojing.beans.vo.Pagination;
import com.jilefojing.beans.vo.UploadFile;
import com.jilefojing.context.beans.vo.UserContext;
import com.jilefojing.controller.base.BaseController;
import com.jilefojing.controller.convent.CommonConvent;
import com.jilefojing.qiniu.beans.enums.BucketEnum;
import com.jilefojing.service.IBannerService;
import com.jilefojing.util.Detect;
import com.jilefojing.util.QiniuUtil;

@Controller
@RequestMapping("banner")
public class BannerController extends BaseController {
	@Autowired
	private IBannerService bannerService;

	@RequestMapping("delete")
	public @ResponseBody
	ResponseData delete(long id, HttpServletRequest request) throws UserContextException {
		ResponseData responseData = new ResponseData();
		try {
			UserContext userContext = super.getUserContext();
			bannerService.delete(id, userContext);
		} catch (UserContextException e) {
			if (e.getResponse() != null) {
				responseData.setResponseEnum(e.getResponse());
			} else {
				responseData.setResponseEnum(ResponseEnum.UNKNOWN);
				responseData.setResponseMessage(e.getMessage());
			}
		}
		return responseData;
	}

	@RequestMapping("add")
	public @ResponseBody
	ResponseData add(Banner banner, HttpServletRequest request) throws UserContextException {
		ResponseData responseData = new ResponseData();
		try {
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String startTimeStr = request.getParameter("startTimeStr");
			String endTimeStr = request.getParameter("endTimeStr");
			if (Detect.notEmpty(startTimeStr)) {
				banner.setStartTime(df.parse(startTimeStr));
			}
			if (Detect.notEmpty(endTimeStr)) {
				banner.setEndTime(df.parse(endTimeStr));
			}

			UserContext userContext = super.getUserContext();
			banner = bannerService.add(banner, userContext);
		} catch (UserContextException e) {
			if (e.getResponse() != null) {
				responseData.setResponseEnum(e.getResponse());
			} else {
				responseData.setResponseEnum(ResponseEnum.UNKNOWN);
				responseData.setResponseMessage(e.getMessage());
			}
		} catch (ParseException e) {
			responseData.setResponseEnum(ResponseEnum.UNKNOWN);
			responseData.setResponseMessage(e.getMessage());
		}
		return responseData;
	}

	@RequestMapping("info.html")
	public String toInfoPage(HttpServletRequest request, long id) throws UserContextException {
		request.setAttribute("banner", CommonConvent.convent2BannerData((EnhancedBanner) bannerService.getEnhanced(id, super.getUserContext())));
		request.setAttribute("imgBucketToken", QiniuUtil.getToken(BucketEnum.IMG));
		request.setAttribute("imgBucketDomain", QiniuUtil.getDomainByBucket(BucketEnum.IMG));
		return "banner/banner_info";
	}

	@RequestMapping("add.html")
	public String toAddPage(HttpServletRequest request) {
		request.setAttribute("imgBucketToken", QiniuUtil.getToken(BucketEnum.IMG));
		request.setAttribute("imgBucketDomain", QiniuUtil.getDomainByBucket(BucketEnum.IMG));
		return "banner/banner_add";
	}

	@RequestMapping(value = "updateCover", method = RequestMethod.POST)
	public @ResponseBody
	ResponseData updateCover(long id, HttpServletRequest request) throws UserContextException, IOException {
		UserContext userContext = super.getUserContext();

		MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;

		MultipartFile coverFile = mulRequest.getFile("coverFile");

		UploadFile coverUploadFile = new UploadFile();
		coverUploadFile.setBytes(coverFile.getBytes());
		coverUploadFile.setSuffix(coverFile.getOriginalFilename().substring(coverFile.getOriginalFilename().lastIndexOf(".") + 1));

		ResponseData responseData = new ResponseData();
		Banner banner = bannerService.updateCover(id, coverUploadFile, userContext);
		responseData.setData(((EnhancedBanner) bannerService.getEnhanced(banner.getId(), userContext)).getCoverUrl());

		return responseData;
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public @ResponseBody
	ResponseData update(Banner banner, String startTimeStr, String endTimeStr, HttpServletRequest request) throws UserContextException {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		UserContext userContext = super.getUserContext();

		ResponseData responseData = new ResponseData();
		try {
			banner.setStartTime(df.parse(startTimeStr));
			banner.setEndTime(df.parse(endTimeStr));

			banner = bannerService.update(banner, userContext);
		} catch (UserContextException e) {
			if (e.getResponse() != null) {
				responseData.setResponseEnum(e.getResponse());
			} else {
				responseData.setResponseEnum(ResponseEnum.UNKNOWN);
				responseData.setResponseMessage(e.getMessage());
			}
		} catch (Exception e) {
			responseData.setResponseEnum(ResponseEnum.UNKNOWN);
			responseData.setResponseMessage(e.getMessage());
		}

		return responseData;
	}

	@RequestMapping("list.html")
	public String toListPage(HttpServletRequest request) {
		return "banner/banner_list";
	}

	@RequestMapping("list")
	public @ResponseBody
	Map<String, Object> getBannerList(String like_title, Short status, Short platform, HttpServletRequest request) throws UserContextException {
		UserContext userContext = super.getUserContext();

		int page = Integer.valueOf(request.getParameter("page"));
		int rows = Integer.valueOf(request.getParameter("rows"));

		String sortsStr = request.getParameter("sort");
		String ordersStr = request.getParameter("order");

		Pagination<EnhancedBanner> pagination = new Pagination<EnhancedBanner>(page, rows, true);
		if (!Detect.notEmpty(sortsStr)) {
			pagination.addOrder(new Order(Banner.COLUMN_SORT, Order.ORDER_DESC)).addOrder(new Order(Banner.COLUMN_UPDATE_TIME, Order.ORDER_DESC));
		} else {
			super.addSorts(sortsStr, ordersStr, Banner.FIELD_SORT, Banner.COLUMN_SORT, pagination);
			super.addSorts(sortsStr, ordersStr, Banner.FIELD_UPDATETIME, Banner.COLUMN_UPDATE_TIME, pagination);
		}

		BannerQuery bannerQuery = new BannerQuery();
		if (status != null && status > 0) {
			bannerQuery.setStatuses(Arrays.asList(new StatusEnumForPublish[] { StatusEnumForPublish.getStatusEnumByCode(status) }));
		}

		if (platform != null && platform > 0) {
			bannerQuery.setPlatforms(Arrays.asList(new PlatformEnumForPublish[] { PlatformEnumForPublish.getPlatformEnumByCode(platform) }));
		}

		bannerQuery.setLike_title(like_title);

		pagination = bannerService.getPagination(bannerQuery, pagination, userContext);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("total", pagination.getCount());
		List<BannerData> bannerDatas = new ArrayList<BannerData>();
		if (Detect.notEmpty(pagination.getItems())) {
			bannerDatas = CommonConvent.convent2BannerDatas(pagination.getItems());
		}
		resultMap.put("rows", bannerDatas);

		return resultMap;
	}

}
